﻿using System;
using System.Data;
using System.Text;
using System.Windows.Forms;
using myFunction.UserSettings;
using MyFunction.SQLiteHelper;

namespace dataDict
{
    /// <summary>
    ///  主窗口
    /// </summary>
    public partial class main : Form
    {
        /// <summary>
        ///  联接字符串
        /// </summary>
        private string ConStr = MyFunction.dbFuncion.dBFunctions.ConnectionStringSQLite;
        /// <summary>
        /// 数据库名
        /// </summary>
        private string databaseName;
        /// <summary>
        ///  过滤内容
        /// </summary>
        public string FilterStr;
        /// <summary>
        ///  main form 构造函数
        /// </summary>
        public main()
        {
            InitializeComponent();
        }

        #region 退出按钮
        /// <summary>
        ///  按钮 -- 退出系统
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripExit_Click(object sender, EventArgs e)
        {
      
            notifyIcon1.Visible = false;
            notifyIcon1.Dispose();
            Close();
            Dispose();
            Application.Exit();
        }
        #endregion

        #region 窗体载入事件
        /// <summary>
        ///  窗体载入事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void main_Load(object sender, EventArgs e)
        {
            //BindDatabase ( ); //加载数据库表列
            FilterStr = "";
            comboBoxGreateType.SelectedIndex = 0;
        }
        #endregion

        #region  显示数据库名
        /// <summary>
        ///   将数据名绑定到 comboBoxDatabase
        /// </summary>
        public void BindDatabase()
        {
            SqliteHelper sqliteHelper = new SqliteHelper(ConStr);
            string cmdText = "select distinct database from u_systable order by upper(database) ";
            comboBoxDatabase.Items.Clear(); //清除原有数据
            if (sqliteHelper.Load(cmdText))
            {

                DataTable dt = sqliteHelper.DataSet.Tables[0];
                foreach (DataRow dr in dt.Rows)
                {
                    comboBoxDatabase.Items.Add(dr[0]);
                }
                if (comboBoxDatabase.Items.Count > 0)
                {
                    comboBoxDatabase.SelectedIndex = 0;
                }

                databaseName = comboBoxDatabase.Text;
                BindSysId(databaseName);
            }
        }
        #endregion

        #region 子系统分类
        /// <summary>
        ///  将子系统分类绑定到 comboBoxSys_id
        /// </summary>
        /// <param name="database"></param>
        private void BindSysId(string database)
        {
            SqliteHelper sqliteHelper = new SqliteHelper(ConStr);
            string cmdText = "select distinct trim(sys_id) from u_systable where database ='" + database + "' order by upper(sys_id) ";
            comboBoxSys_id.Items.Clear(); //清除原的数据
            if (sqliteHelper.Load(cmdText))
            {
                comboBoxSys_id.Items.Add("全部分类");
                DataTable dt = sqliteHelper.DataSet.Tables[0];
                foreach (DataRow dr in dt.Rows)
                {
                    comboBoxSys_id.Items.Add(dr[0]);
                }
                if (comboBoxSys_id.Items.Count > 0)
                {
                    comboBoxSys_id.SelectedIndex = 0;
                }
            }
        }
        #endregion

        #region 显示同步窗口
        /// <summary>
        ///  菜单 -- 显示同步窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripsync_Click(object sender, EventArgs e)
        {
            syncform frm = new syncform();
            frm.ShowDialog(this);
            BindDatabase();
        }
        #endregion

        #region 保存数据
        /// <summary>
        ///  菜单 -- 保存数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButtonSave_Click(object sender, EventArgs e)
        {
            SaveTableData();
        }
        #endregion

        #region 更新数据库列表
        /// <summary>
        /// 控件 comboBoxDatabase 进入时更新数据库列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBoxDatabase_Enter(object sender, EventArgs e)
        {
            BindDatabase();

            myUserSetting mySetting = new myUserSetting();
            comboBoxDatabase.Text = mySetting.DefaultDatabase;
        }
        #endregion

        #region 更新子系统分类列表
        /// <summary>
        ///  控件comboBoxSys_id值变化时，更新子系统分类列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBoxSys_id_SelectedIndexChanged(object sender, EventArgs e)
        {
            string SysId = comboBoxSys_id.Text;
            if (SysId == "全部分类")
            {
                u_systableTableAdapter.FillByDatabase(dataSet1.u_systable, databaseName);
            }
            else
            {
                u_systableTableAdapter.FillBySysId(dataSet1.u_systable, databaseName, SysId);
            }
        }
        #endregion

        #region 根据当前表名，显示表相关的数据，在取新数据前保存旧数据
        /// <summary>
        ///  控件 dgvTable,进行某行， 根据当前表名，显示表相关的数据，在取新数据前保存旧数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvTable_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            var formattedValue = dgvTable.Rows[e.RowIndex].Cells["tablenameCol"].FormattedValue;
            if (formattedValue != null)
            {
                string Tablename = formattedValue.ToString();
                u_syscolcommentTableAdapter.FillByTableName(dataSet1.u_syscolcomment, databaseName, Tablename);
            }
        }

        #endregion

        #region  dgvTable 离开事件，调用保存保存 table 数据事件
        /// <summary>
        ///  控制  dgvTable 离开事件，调用保存保存 table 数据事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvTable_Leave(object sender, EventArgs e)
        {
            SaveTableData();
        }
        #endregion

        #region 保存數據
        /// <summary>
        ///  方法：保存 u_systable  表数据
        /// </summary>
        private void SaveTableData()
        {
            dgvTable.EndEdit();
            usystableBindingSource.EndEdit();
            //检查是否有修改，如有修改，则更新修改日期
            foreach (DataRow dr in dataSet1.u_systable.Rows)
            {
                if (dr.RowState == DataRowState.Modified)
                {
                    dr["lastupdate"] = DateTime.Now.ToString("yyyy/MM/dd HH:mm");
                }
            }
            try
            {
                u_systableTableAdapter.Update(dataSet1.u_systable);
            }
            catch (Exception ex)
            {
                throw ex;
            }


        }

        #endregion

        #region 保存列数据
        /// <summary>
        ///  方法：保存u_syscolcomment 数据
        /// </summary>
        private void SaveColumnData()
        {
            dgvColum.EndEdit();
            usyscolcommentBindingSource.EndEdit();
            //检测是否有更新行的，如有，则修改lastupdate 字段
            string LastUpdae = DateTime.Now.ToString("yyyy/MM/dd HH:mm");
            foreach (DataRow dr in dataSet1.u_syscolcomment.Rows)
            {
                if (dr.RowState == DataRowState.Modified)
                {
                    dr["lastupdate"] = LastUpdae;
                }

            }
            try
            {
                u_syscolcommentTableAdapter.Update(dataSet1.u_syscolcomment);
            }
            catch (Exception ex)
            {

                throw ex;
            }

        }
        #endregion

        #region 离开时保存列数据
        /// <summary>
        ///  控件 dgvColum 离开时保存列数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvColum_Leave(object sender, EventArgs e)
        {
            SaveColumnData();
        }
        #endregion

        #region 选择生成语句
        /// <summary>
        ///  控件：值变化时，设定相关标签的名称
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string CreateType = comboBoxGreateType.Text.Trim();
            switch (CreateType)
            {
                case "Select 语句":
                    textBoxRowName.Visible = false;
                    textBoxObjectRow.Visible = false;
                    labelObjectName.Visible = false;
                    LableRowName.Visible = false;
                    break;
                case "PB DW 格式":
                    textBoxRowName.Visible = true;
                    textBoxObjectRow.Visible = true;
                    labelObjectName.Visible = true;
                    LableRowName.Visible = true;
                    labelObjectName.Text = "DW 名称：";
                    LableRowName.Text = "行变量：";
                    textBoxObjectRow.Text = "dw_input";
                    textBoxRowName.Text = "ll_row";
                    break;
                case "DataRow 赋值":
                    textBoxRowName.Visible = true;
                    textBoxObjectRow.Visible = true;
                    labelObjectName.Visible = true;
                    LableRowName.Visible = true;
                    labelObjectName.Text = "DataRow 名称：";
                    break;
            }
        }
        #endregion


        #region 生成语句按钮
        /// <summary>
        ///  按钮 :调用相应的方法生成语句
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonCreate_Click(object sender, EventArgs e)
        {
            string CreateType = comboBoxGreateType.Text.Trim();
            string Statement = "";
            switch (CreateType)
            {
                case "Select 语句":
                    Statement = CreateSql();
                    break;
                case "PB DW 格式":
                    Statement = CreateDWFormat1();
                    break;
                case "DataRow 赋值":
                    Statement = CreateDatarow1();
                    break;

            }
            if (Statement != "")
            {
                ShowStatement frm = new ShowStatement(Statement);
                frm.ShowDialog(this);
            }
        }
        #endregion

        #region 生成SQL语句
        /// <summary>
        ///  方法： 生成SQL语句
        /// </summary>
        /// <returns>SQL语句</returns>
        private string CreateSql()
        {
            StringBuilder CreateStatement = new StringBuilder();
            CreateStatement.Append("select ");
            string ReturnValue = "";
            bool selectfield = false;
            foreach (DataGridViewRow dgvr in dgvColum.Rows)
            {
                var formattedValue = dgvr.Cells["SelectItem"].FormattedValue;
                bool selectitem = formattedValue != null && bool.Parse(formattedValue.ToString());
                var value = dgvr.Cells["fieldname"].FormattedValue;
                if (value != null)
                {
                    string FieldName = value.ToString();
                    //string TableName = dgvr.Cells["tablename"].FormattedValue.ToString ( );
                    if (selectitem)
                    {
                        CreateStatement.Append(FieldName + ", \r\n");
                        selectfield = true;
                    }
                }
            }
            if (selectfield)
            {
                CreateStatement.Remove(CreateStatement.Length - 4, 1);

                var formattedValue = dgvColum.Rows[0].Cells["tablename"].FormattedValue;
                if (formattedValue != null)
                {
                    string TableName = formattedValue.ToString();
                    CreateStatement.Append(" from " + TableName);
                }
                ReturnValue = CreateStatement.ToString();
            }

            return ReturnValue;
        }
        #endregion

        #region 生成DW语句1
        /// <summary>
        ///  方法：生成DW语句
        /// </summary>
        /// <returns>DW语句</returns>
        private string CreateDWFormat1()
        {
            StringBuilder CreateStatement = new StringBuilder();
            string ReturnValue = "";
            bool selectfield = false;
            string dwname = textBoxObjectRow.Text.Trim();
            string rowname = textBoxRowName.Text.Trim();
            if (string.IsNullOrEmpty(dwname) || string.IsNullOrEmpty(rowname))
            {
                return ReturnValue;
            }

            foreach (DataGridViewRow dgvr in dgvColum.Rows)
            {
                var formattedValue = dgvr.Cells["SelectItem"].FormattedValue;
                bool selectitem = formattedValue != null && bool.Parse(formattedValue.ToString());
                string FieldName = dgvr.Cells["fieldname"].FormattedValue.ToString().Trim();

                //string TableName = dgvr.Cells["tablename"].FormattedValue.ToString ( );
                if (selectitem)
                {
                    CreateStatement.Append(dwname + ".object." + FieldName + "[" + rowname + "] = \r\n");
                    selectfield = true;
                }

            }
            if (selectfield)
            {
                ReturnValue = CreateStatement.ToString();
            }

            return ReturnValue;
        }
        #endregion

        #region 生成C#的Datarow 赋值格式语句1
        /// <summary>
        ///  方法： 生成C#的Datarow 赋值格式语句
        /// </summary>
        /// <returns>C#的Datarow 赋值格式语句</returns>
        private string CreateDatarow1()
        {
            StringBuilder CreateStatement = new StringBuilder();
            string ReturnValue = "";
            bool selectfield = false;
            string dwname = textBoxObjectRow.Text.Trim();

            if (string.IsNullOrEmpty(dwname))
            {
                return ReturnValue;
            }

            foreach (DataGridViewRow dgvr in dgvColum.Rows)
            {
                bool selectitem = bool.Parse(dgvr.Cells["SelectItem"].FormattedValue.ToString());
                string FieldName = dgvr.Cells["fieldname"].FormattedValue.ToString().Trim();

                //string TableName = dgvr.Cells["tablename"].FormattedValue.ToString ( );
                if (selectitem)
                {
                    CreateStatement.Append(dwname + "[\"" + FieldName + "\"] =" + FieldName + " \r\n");
                    selectfield = true;
                }

            }
            if (selectfield)
            {
                ReturnValue = CreateStatement.ToString();
            }

            return ReturnValue;
        }

        #endregion

        #region 任务栏图标点击事件
        /// <summary>
        ///  任务栏图标点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            Show();
            WindowState = FormWindowState.Maximized;
            Activate();
            ShowInTaskbar = true;
        }
        #endregion

        #region 窗体大小变化，最小化放图标放入到托盘架中
        /// <summary>
        ///  事件：窗体大小变化，最小化放图标放入到托盘架中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void main_SizeChanged(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                ShowInTaskbar = false;
                Hide(); //或者是Visible = false;
                notifyIcon1.Visible = true;
            }
        }
        #endregion

        #region 字段选中按钮
        /// <summary>
        ///  按钮：全选或反选dgvColum 的行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonSelectAll_Click(object sender, EventArgs e)
        {
            bool SelectValue;
            if (buttonSelectAll.Text == "全选")
            {
                buttonSelectAll.Text = "反选";
                SelectValue = true;
            }
            else
            {
                buttonSelectAll.Text = "全选";
                SelectValue = false;
            }

            foreach (DataGridViewRow dgvr in dgvColum.Rows)
            {
                dgvr.Cells["SelectItem"].Value = SelectValue;
            }
        }
        #endregion

        #region 设定菜单
        /// <summary>
        ///  菜单： 显示设定窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripSetup_Click(object sender, EventArgs e)
        {
            SetUpFrm frm = new SetUpFrm();
            frm.ShowDialog(this);
        }
        #endregion

        #region 项目下拉列表更新
        /// <summary>
        ///  控件： comboBoxSys_id 进入时更新项目下拉列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBoxSys_id_Enter(object sender, EventArgs e)
        {
            BindSysId(databaseName);
        }
        #endregion

        #region 表名过滤
        /// <summary>
        ///  按钮：显示过滤窗口，返来过滤字串
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBoxFilter_MouseClick(object sender, MouseEventArgs e)
        {
            FilterFrm frm = new FilterFrm();
            frm.ShowDialog(this);
            //MessageBox.Show ( FilterStr );
            usystableBindingSource.Filter = FilterStr;
        }
        #endregion

        #region 显示查找所有字段窗体
        /// <summary>
        ///  按钮：显示查找窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButtonSearch_Click(object sender, EventArgs e)
        {
            databaseName = comboBoxDatabase.Text.Trim();
            FieldSearch frm = new FieldSearch(databaseName);
            frm.ShowDialog(this);
        }
        #endregion

        #region 控件dgvColum 数据错误处理，可以不写代码，但必须要
        /// <summary>
        ///  控件dgvColum 数据错误处理，可以不写代码，但必须要
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvColum_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }
        #endregion
        /// <summary>
        ///  数据库列表变化时，重新生成分类
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBoxDatabase_SelectedIndexChanged(object sender, EventArgs e)
        {
            databaseName = comboBoxDatabase.Text;
            BindSysId(databaseName);
            u_systableTableAdapter.FillByDatabase(dataSet1.u_systable, databaseName);
        }

        private void main_FormClosed(object sender, FormClosedEventArgs e)
        {
            myUserSetting mySetting = new myUserSetting();
            mySetting.DefaultDatabase = comboBoxDatabase.Text;
            mySetting.Save();
        }
    }
}